/*********************************************************************************
 * 文件名称: aliyun_iot_auth.c
 * 版       本:
 * 日       期: 2016-05-30
 * 描       述:
 * 其       它:
 * 历       史:
 **********************************************************************************/
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "aliyun_iot_platform_stdio.h"
#include "aliyun_iot_platform_network.h"
#include "aliyun_iot_platform_persistence.h"
#include "aliyun_iot_platform_memory.h"
#include "aliyun_iot_common_datatype.h"
#include "aliyun_iot_common_error.h"
#include "aliyun_iot_common_log.h"
#include "aliyun_iot_common_config.h"
#include "aliyun_iot_common_base64.h"
#include "aliyun_iot_common_json.h"
#include "aliyun_iot_common_md5.h"
#include "aliyun_iot_common_httpclient.h"
#include "aliyun_iot_common_hmac.h"
#include "aliyun_iot_auth.h"
#include "aliyun_iot_mqtt_internal.h"
#include "xrj_mqtt_client.h"

#define  MQTT_DEVICE_NOT_EXSIT_ERRORCODE "InvalidDevice"

/***********************************************************
* 全局变量: g_userInfo
* 描       述: 用户信息
* 说       明:
************************************************************/
ALIYUN_IOT_USER_INFO_S g_userInfo;


/***********************************************************
* 函数名称: aliyun_iot_get_response_XRJ
* 描       述: 鉴权响应信息的解析
* 输入参数: const INT8* at    httpclient获取的鉴权信息
* 输出参数: AUTH_INFO_S *info 解析的鉴权结果
* 返 回  值: 0：成功  -1：失败
* 说       明: httpclient获取的鉴权响应信息进行Json解析，获得鉴权内容
************************************************************/
static INT32 aliyun_iot_get_response_XRJ(const INT8* at)
{
INT8   servers[64]; 	
ALIYUN_IOT_USER_INFO_S 	* userInfo = &g_userInfo;	
    cJSON *jsonObj = aliyun_iot_common_json_parse(at);
    if(NULL == jsonObj)
    {
        WRITE_IOT_ERROR_LOG("get NULL pointer of json!");
        return FAIL_RETURN;
    }

	snprintf(userInfo->PubTopic,TOPIC_LEN,"%s", XRJ_BOARD_INFO.TopicUpdate);
	snprintf(userInfo->SubTopic,TOPIC_LEN,"%s", XRJ_BOARD_INFO.TopicGet);
	snprintf(userInfo->clientId,CLIENT_ID_LEN,"ucos-ii");
	
    cJSON *result = jsonObj->child;
    while (result)
    {
		if (!strcmp(result->string, "connectHost"))
        {
            memset(servers,0x0,64);
            strncpy(servers,result->valuestring,HOST_ADDRESS_LEN);
					
			//生成host address
			INT32 len = 0;
			INT8* position = strchr(servers,'|');
			if(NULL == position)
			{

					WRITE_IOT_ERROR_LOG("the format of servers is error!");
					return FAIL_RETURN;
			}

			//根据协议使用类型生成host address
			INT8 portString[8];
			memset(portString,0x0,8);

			INT8* portStart = strchr(servers,':');
			if(NULL == portStart)
			{
					WRITE_IOT_ERROR_LOG("the format of servers is error!");
					return FAIL_RETURN;
			}

			memset(userInfo->hostAddress,0x0,HOST_ADDRESS_LEN);
			len = portStart - servers;
			strncpy(userInfo->hostAddress,servers,len);

			memset(userInfo->port,0x0,HOST_PORT_LEN);
			len = position - portStart;
			strncpy(portString,(portStart+1),len-1);
			memcpy(userInfo->port, portString, strlen(portString));

			WRITE_IOT_DEBUG_LOG("portString:%s",portString);
			WRITE_IOT_DEBUG_LOG("userInfo->port:%s",userInfo->port);
			WRITE_IOT_DEBUG_LOG("userInfo-hostAddress:%s",userInfo->hostAddress);

						
        }			
		else if (!strcmp(result->string, "userName"))
        {
            memset(userInfo->userName,0x0,USER_NAME_LEN);
            strncpy(userInfo->userName,result->valuestring,USER_NAME_LEN);
						WRITE_IOT_DEBUG_LOG("userName: %s",userInfo->userName);
        }
		else if (!strcmp(result->string, "password"))
        {
            memset(userInfo->password,0x0,HOST_ADDRESS_LEN);
            strncpy(userInfo->password,result->valuestring,64);	
						
						WRITE_IOT_DEBUG_LOG("password: %s",userInfo->password);
        }
		else if (!strcmp(result->string, "topic"))
        {
			snprintf(userInfo->PubTopic,TOPIC_LEN,"%s%s/",result->valuestring, XRJ_BOARD_INFO.TopicUpdate);
			snprintf(userInfo->SubTopic,TOPIC_LEN,"%s%s/",result->valuestring, XRJ_BOARD_INFO.TopicGet);	
			WRITE_IOT_DEBUG_LOG("topic pub: %s",userInfo->PubTopic);
			WRITE_IOT_DEBUG_LOG("topic sub: %s",userInfo->SubTopic);
        }		
		else if (!strcmp(result->string, "clientId"))
        {
			snprintf(userInfo->clientId,CLIENT_ID_LEN,"%s",result->valuestring);
			WRITE_IOT_DEBUG_LOG("clientID : %s",userInfo->clientId);
        }			
//--------------------------------------------------------------------------				
        result = result->next;
    }

    //删除资源
    aliyun_iot_common_json_delete(jsonObj);

    return SUCCESS_RETURN;
}



//http://112.111.40.25:8081/xrj-api-web/api/device/auth/596d6d79a3dbf27960a4889c

#define XRJ_Resp_Len				MQTT_MSG_SIZE_RX

INT32 aliyun_iot_auth_XRJ(void)
{
INT8 	postString[128];
INT16 	responseSize;

//获得存放用户信息的内存空间

//拉取IP信息
	sprintf(postString, "%s%s",XRJ_BOARD_INFO.HOST_NAME,XRJ_BOARD_INFO.DEVICE_UUID_STRING);
	responseSize = XRJ_Resp_Len;
    	
    httpclient_t client;
    httpclient_data_t client_data;
    memset(&client,0x0,sizeof(httpclient_t));
    memset(&client_data,0x0,sizeof(httpclient_data_t));		
	
	INT8 *response_buf = aliyun_iot_memory_malloc(responseSize);
    if (response_buf == NULL)
    {
        WRITE_IOT_ERROR_LOG("malloc http response buf failed!");
        return FAIL_RETURN;
    }
		
    memset(response_buf,0x0,responseSize);
    client_data.response_buf = response_buf;
    client_data.response_buf_len = responseSize;
	
//-----post	
	IOT_RETURN_CODES_E result = aliyun_iot_common_post(&client, postString, HTTP_PORT, &client_data);
    if(SUCCESS_RETURN != result)
    {
        aliyun_iot_memory_free(response_buf);
        WRITE_IOT_ERROR_LOG("run aliyun_iot_common_post error!");
        return result;
    }
	
	result = (IOT_RETURN_CODES_E)aliyun_iot_get_response_XRJ(response_buf);
	
	if(SUCCESS_RETURN != result)
    {
        aliyun_iot_memory_free(response_buf);
        WRITE_IOT_ERROR_LOG("run aliyun_iot_get_response error!");
        return result;
    }

    aliyun_iot_memory_free(response_buf);
	
    return SUCCESS_RETURN;

}


/***********************************************************
* 函数名称: aliyun_iot_auth_init
* 描       述: auth初始化函数
* 输入参数: VOID
* 输出参数: VOID
* 返 回  值: 0 成功，-1 失败
* 说       明: 初始化日志级别，设备信息，分配authinfo内存，
*           鉴权信息文件的保存路径
************************************************************/
INT32 aliyun_iot_auth_init_XRJ()
{		
//	aliyun_iot_common_set_log_level(DEBUG_IOT_LOG);
	aliyun_iot_common_set_log_level(INFO_IOT_LOG);
    aliyun_iot_common_log_init();
	

    WRITE_IOT_NOTICE_LOG("auth init success!");
    return SUCCESS_RETURN;
}

/***********************************************************
* 函数名称: aliyun_iot_auth_release
* 描       述: auth释放函数
* 输入参数: VOID
* 输出参数: VOID
* 返 回  值: 0:成功 -1:失败
* 说      明: 释放authInfo内存
************************************************************/
INT32 aliyun_iot_auth_release_XRJ()
{
    WRITE_IOT_NOTICE_LOG("auth release!");
    aliyun_iot_common_log_release();
    return SUCCESS_RETURN;
}
